<template>
  <div class="home">
    <h1>首页</h1>
    <p>欢迎使用排班管理系统</p>
    <router-link to="/shiftarrangementseasy">排班管理（简单版）</router-link>
    <a-button type="primary" @click="handleLogin">登录</a-button>
    <router-link to="/about">关于我们</router-link>
    <a-button type="primary" @click="loginAfter">登录后请求接口</a-button>
  </div>
</template>

<script setup lang="ts">
// 首页组件逻辑
import { useRouter } from 'vue-router'
import * as dd from 'dingtalk-jsapi'; 
import { onMounted,ref } from 'vue';
// 导入登录接口
import { login, loginAuth } from '@/api/index';
import { showSuccessToast, showFailToast } from 'vant';
// 导入认证相关工具函数
// @ts-ignore
import { setToken, setDingUserInfo } from '@/utils/auth';
const router = useRouter()
// 设置默认值，确保即使没有路由传参也能使用
const corpid = ref(import.meta.env.VITE_APP_CORPID)
const handleLogin = async () => {
dd.requestAuthCode({
  corpId: corpid.value,
  clientId: import.meta.env.VITE_APP_CLIENT_ID,
  onSuccess: async function (result:any) {
    console.log('登录code:', result.code)
    try {
        // 调用登录接口
        const response = await login(result.code);
        console.log('登录成功:', response);
        
        // 保存token和用户信息
        if (response && response.data) {
          // 保存token到Cookie
          if (response.data.auth_token || response.data.token) {
            setToken(response.data.auth_token || response.data.token);
          }
          
          // 保存用户信息到localStorage
          if (response.data.dingUserInfo || response.data.userInfo) {
            setDingUserInfo(response.data.dingUserInfo || response.data.userInfo);
          }
          
          showSuccessToast('登录成功');
        } else {
          showFailToast('登录数据格式异常');
        }
      } catch (error) {
        console.error('登录失败:', error);
        showFailToast('登录失败，请重试');
      }
    /*{
        code: 'hYLK98jkf0m' //string authCode
    }*/
  },
  onFail: function (err:any) {
    console.error('获取登录code失败:', err);
    showFailToast('获取登录授权失败');
  },
});
}

const loginAfter = async()=>{
  await loginAuth()
}

//加载时获取路由传参
onMounted(() => {
  let corpidTemp = router.currentRoute.value.query.corpid
  if (corpidTemp) {
    console.log('路由传参corpid:', corpidTemp)
    corpid.value = corpidTemp.toString();
  }
})


</script>

<style scoped>
.home {
  padding: 20px;
  text-align: center;
}

h1 {
  color: #333;
}

a {
  color: #42b983;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
</style>
